<template>
  <div class="dashboard">
    <!-- 系统状态概览 -->
    <a-row :gutter="[16, 16]" class="overview-section">
      <!-- 系统状态卡片 -->
      <a-col :xs="24" :lg="16">
        <a-card class="system-status-card">
          <template #title>
            <a-space>
              <RocketOutlined />
              <span>Git Webhook 自动部署系统</span>
            </a-space>
          </template>
          <template #extra>
            <a-tag :color="currentDeploy.isDeploying ? 'processing' : 'success'">
              {{ currentDeploy.isDeploying ? '部署中' : '系统就绪' }}
            </a-tag>
          </template>
          <p class="system-description">
            基于Git Webhook的自动化部署系统，监听仓库Push事件，自动拉取代码、执行构建并部署到指定目录。
            支持多种认证方式，提供完整的部署历史和日志管理功能。
          </p>
        </a-card>
      </a-col>
      
      <!-- 快速操作卡片 -->
      <a-col :xs="24" :lg="8">
        <a-card class="quick-actions-card">
          <template #title>
            <a-space>
              <ControlOutlined />
              <span>快速操作</span>
            </a-space>
          </template>
          <div class="quick-actions">
            <a-button 
              type="primary" 
              size="large"
              block
              :loading="deployLoading"
              @click="showManualDeployModal"
              :disabled="currentDeploy.isDeploying"
              class="deploy-button"
            >
              <template #icon>
                <RocketOutlined />
              </template>
              手动部署
            </a-button>
            <div class="action-links">
              <router-link to="/config">
                <a-button type="link" size="small">系统配置</a-button>
              </router-link>
              <router-link to="/history">
                <a-button type="link" size="small">部署历史</a-button>
              </router-link>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 统计信息 -->
    <a-row :gutter="[16, 16]" class="stats-section">
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic
            title="总部署次数"
            :value="stats.total"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix>
              <DeploymentUnitOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic
            title="成功部署"
            :value="stats.success"
            :value-style="{ color: '#52c41a' }"
          >
            <template #prefix>
              <CheckCircleOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic
            title="失败部署"
            :value="stats.failed"
            :value-style="{ color: '#ff4d4f' }"
          >
            <template #prefix>
              <CloseCircleOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :xs="12" :sm="6">
        <a-card class="stat-card">
          <a-statistic
            title="成功率"
            :value="successRate"
            suffix="%"
            :value-style="{ color: successRate >= 80 ? '#52c41a' : '#faad14' }"
          >
            <template #prefix>
              <TrophyOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 部署控制台 -->
    <a-card class="deploy-console-card">
      <template #title>
        <a-space>
          <MonitorOutlined />
          <span>部署控制台</span>
        </a-space>
      </template>
      
      <!-- 当前状态提示 -->
      <a-alert
        :message="currentDeploy.isDeploying ? '部署进行中...' : '系统就绪，可以开始新的部署'"
        :type="currentDeploy.isDeploying ? 'info' : 'success'"
        :description="getDeployDescription()"
        show-icon
        class="status-alert"
      />
      
      <!-- 部署进度条 -->
      <div v-if="currentDeploy.isDeploying && currentDeployDetail" class="deploy-progress-section">
        <a-divider orientation="left">
          <span class="progress-title">部署进度</span>
        </a-divider>
        
        <div class="progress-container">
          <a-progress 
            :percent="getDeployProgress()" 
            :status="getProgressStatus()"
            :stroke-color="getProgressColor()"
            :show-info="true"
            :stroke-width="8"
            class="deploy-progress"
          />
          
          <div class="progress-info">
            <a-row justify="space-between" align="middle">
              <a-col>
                <span class="progress-message">
                  <LoadingOutlined v-if="currentDeploy.isDeploying" spin style="margin-right: 8px;" />
                  {{ currentDeployDetail.message || '正在处理...' }}
                </span>
              </a-col>
              <a-col>
                <a-tag :color="getStatusColor(currentDeployDetail.status)">
                  {{ getStatusText(currentDeployDetail.status) }}
                </a-tag>
              </a-col>
            </a-row>
          </div>
          
          <!-- 部署详细信息 -->
          <div class="deploy-details" v-if="currentDeployDetail.createdAt">
            <a-row :gutter="16">
              <a-col :xs="24" :sm="8">
                <a-statistic 
                  title="开始时间" 
                  :value="formatTime(currentDeployDetail.createdAt)"
                  :value-style="{ fontSize: '14px' }"
                />
              </a-col>
              <a-col :xs="12" :sm="8">
                <a-statistic 
                  title="运行时长" 
                  :value="getDeployDuration()"
                  suffix="秒"
                  :value-style="{ fontSize: '14px' }"
                />
              </a-col>
              <a-col :xs="12" :sm="8">
                <a-statistic 
                  title="部署ID" 
                  :value="currentDeploy.currentDeployId"
                  :value-style="{ fontSize: '14px' }"
                />
              </a-col>
            </a-row>
          </div>
        </div>
      </div>
    </a-card>

    <!-- 最近部署记录 -->
    <a-card class="recent-history-card">
      <template #title>
        <a-space>
          <HistoryOutlined />
          <span>最近部署记录</span>
        </a-space>
      </template>
      <template #extra>
        <router-link to="/history">
          <a-button type="link">查看全部</a-button>
        </router-link>
      </template>
      
      <a-list
        :data-source="recentHistory"
        :loading="historyLoading"
        class="history-list"
      >
        <template #renderItem="{ item }">
          <a-list-item class="history-item">
            <template #actions>
              <a @click="viewDeployLogs(item.id)" class="log-link">查看日志</a>
            </template>
            <a-list-item-meta>
              <template #title>
                <a-space wrap>
                  <a-tag :color="getStatusColor(item.status)" class="status-tag">
                    {{ getStatusText(item.status) }}
                  </a-tag>
                  <span class="deploy-message">{{ item.message || '部署任务' }}</span>
                  <a-tag color="blue" v-if="item.branch" class="branch-tag">{{ item.branch }}</a-tag>
                </a-space>
              </template>
              <template #description>
                <a-space wrap class="deploy-meta">
                  <span>{{ formatTime(item.timestamp) }}</span>
                  <span v-if="item.author">by {{ item.author }}</span>
                  <span v-if="item.duration">耗时: {{ formatDuration(item.duration) }}</span>
                </a-space>
              </template>
            </a-list-item-meta>
          </a-list-item>
        </template>
      </a-list>
    </a-card>

    <!-- 手动部署模态框 -->
    <a-modal
      v-model:open="manualDeployModalVisible"
      title="手动触发部署"
      @ok="handleManualDeploy"
      :confirm-loading="deployLoading"
    >
      <a-form :model="manualDeployForm" layout="vertical">
        <a-form-item label="目标分支" name="branch">
          <a-input 
            v-model:value="manualDeployForm.branch" 
            placeholder="留空使用配置的默认分支"
          />
        </a-form-item>
        <a-form-item label="部署说明" name="message">
          <a-textarea 
            v-model:value="manualDeployForm.message" 
            placeholder="请输入本次部署的说明信息"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 日志查看模态框 -->
    <a-modal
      v-model:open="logsModalVisible"
      title="部署日志"
      :footer="null"
      width="80%"
      :body-style="{ padding: 0 }"
    >
      <div style="height: 500px; overflow-y: auto; padding: 16px; background: #f5f5f5;">
        <div v-if="currentLogs.length === 0" style="text-align: center; color: #999;">
          暂无日志信息
        </div>
        <div v-else>
          <div 
            v-for="(log, index) in currentLogs" 
            :key="index"
            :class="['log-item', `log-${log.level || 'info'}`]"
            style="margin-bottom: 8px; padding: 8px; border-radius: 4px; font-family: monospace;"
          >
            <span class="log-time">{{ formatTime(log.timestamp) }}</span>
            <span class="log-level">{{ (log.level || 'INFO').toUpperCase() }}</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import api from '../services/api'
import {
  DeploymentUnitOutlined,
  TrophyOutlined,
  RocketOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  LoadingOutlined,
  ControlOutlined,
  MonitorOutlined,
  HistoryOutlined
} from '@ant-design/icons-vue'

// 响应式数据
const stats = ref({
  total: 0,
  success: 0,
  failed: 0,
  running: 0,
  pending: 0
})

const currentDeploy = ref({
  isDeploying: false,
  currentDeployId: null,
  startTime: null,
})

const currentDeployDetail = ref(null)
const recentHistory = ref([])
const currentLogs = ref([])

// 加载状态
const deployLoading = ref(false)
const historyLoading = ref(false)

// 模态框状态
const manualDeployModalVisible = ref(false)
const logsModalVisible = ref(false)

// 表单数据
const manualDeployForm = ref({
  branch: '',
  message: ''
})

// 定时器
let statusTimer = null
let deployDetailTimer = null

// 计算属性
const successRate = computed(() => {
  if (stats.value.total === 0) return 0
  return Math.round((stats.value.success / stats.value.total) * 100)
})

// 方法
const getDeployDescription = () => {
  if (currentDeploy.value.isDeploying) {
    return `部署ID: ${currentDeploy.value.currentDeployId} | 开始时间: ${formatTime(currentDeploy.value.createdAt)}`
  }
  return '点击手动部署按钮开始新的部署任务'
}

const getProgressStatus = () => {
  if (!currentDeployDetail.value) return 'normal'
  const status = currentDeployDetail.value.status
  if (status === 'failed') return 'exception'
  if (status === 'success') return 'success'
  return 'active'
}

const getProgressColor = () => {
  if (!currentDeployDetail.value) return '#1890ff'
  const status = currentDeployDetail.value.status
  if (status === 'failed') return '#ff4d4f'
  if (status === 'success') return '#52c41a'
  return '#1890ff'
}

const getStatusColor = (status) => {
  const colors = {
    success: 'green',
    failed: 'red',
    running: 'blue',
    pending: 'orange'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    success: '成功',
    failed: '失败',
    running: '运行中',
    pending: '等待中'
  }
  return texts[status] || status
}

const getDeployProgress = () => {
  if (!currentDeploy.value) return 0
  // 优先使用实时状态中的进度
  if (currentDeploy.value.progress !== undefined) {
    return currentDeploy.value.progress
  }
  // 回退到详细信息中的进度
  if (currentDeployDetail.value && currentDeployDetail.value.progress !== undefined) {
    return currentDeployDetail.value.progress
  }
  return 0
}

const getDeployDuration = () => {
  if (!currentDeployDetail.value || !currentDeployDetail.value.createdAt) return 0
  const startTime = new Date(currentDeployDetail.value.createdAt).getTime()
  const now = Date.now()
  return Math.floor((now - startTime) / 1000)
}

const formatTime = (timestamp) => {
  if (!timestamp) return '-'
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}

const formatDuration = (duration) => {
  if (!duration) return '-'
  if (duration < 1000) return `${duration}ms`
  return `${Math.round(duration / 1000)}s`
}

// API调用方法
const loadStats = async () => {
  try {
    const response = await api.getStats()
    if (response.success) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

const loadCurrentDeployStatus = async () => {
  try {
    const response = await api.getCurrentDeployStatus()
    if (response.success) {
      currentDeploy.value = response.data
      
      // 如果有正在进行的部署，获取详细信息
      if (currentDeploy.value.isDeploying && currentDeploy.value.currentDeployId) {
        await loadDeployDetail(currentDeploy.value.currentDeployId)
      }
    }
  } catch (error) {
    console.error('加载部署状态失败:', error)
  }
}

const loadDeployDetail = async (deployId) => {
  try {
    const response = await api.getDeployStatus(deployId)
    if (response.success) {
      currentDeployDetail.value = response.data
    }
  } catch (error) {
    console.error('加载部署详情失败:', error)
  }
}

const loadRecentHistory = async () => {
  try {
    historyLoading.value = true
    const response = await api.getHistory({ limit: 5, offset: 0 })
    if (response.success) {
      recentHistory.value = response.data || []
    }
  } catch (error) {
    console.error('加载最近历史失败:', error)
  } finally {
    historyLoading.value = false
  }
}

const showManualDeployModal = () => {
  manualDeployForm.value = {
    branch: '',
    message: ''
  }
  manualDeployModalVisible.value = true
}

const handleManualDeploy = async () => {
  try {
    deployLoading.value = true
    const response = await api.manualDeploy(manualDeployForm.value)
    if (response.success) {
      message.success('部署任务已启动')
      manualDeployModalVisible.value = false
      // 手动部署后立即加载最新状态
      await loadCurrentDeployStatus()
      await loadStats()
      await loadRecentHistory()
    } else {
      message.error(response.message || '启动部署失败')
    }
  } catch (error) {
    message.error('启动部署失败')
  } finally {
    deployLoading.value = false
  }
}

const viewDeployLogs = async (deployId) => {
  try {
    const response = await api.getDeployLogs(deployId)
    if (response.success) {
      // 处理日志数据结构，与History组件保持一致
      if (response.data && response.data.logs) {
        currentLogs.value = response.data.logs || []
      } else {
        currentLogs.value = response.data || []
      }
      logsModalVisible.value = true
    } else {
      message.error('获取日志失败')
    }
  } catch (error) {
    message.error('获取日志失败')
  }
}

// 生命周期
onMounted(async () => {
  // 初始化加载数据
  await loadStats()
  await loadCurrentDeployStatus()
  await loadRecentHistory()
  
  // 设置定时器定期刷新状态
  statusTimer = setInterval(async () => {
    await loadCurrentDeployStatus()
    if (currentDeploy.value.isDeploying) {
      await loadStats()
    }
  }, 5000)
  
  // 如果有正在进行的部署，更频繁地更新详情
  deployDetailTimer = setInterval(async () => {
    if (currentDeploy.value.isDeploying && currentDeploy.value.currentDeployId) {
      await loadDeployDetail(currentDeploy.value.currentDeployId)
    }
  }, 2000)
})

onUnmounted(() => {
  if (statusTimer) {
    clearInterval(statusTimer)
  }
  if (deployDetailTimer) {
    clearInterval(deployDetailTimer)
  }
})
</script>

<style scoped>
.dashboard {
  padding: 0;
  max-width: 1200px;
  margin: 0 auto;
}

/* 概览区域 */
.overview-section {
  margin-bottom: 24px;
}

.system-status-card {
  height: 100%;
}

.system-description {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.quick-actions-card {
  height: 100%;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.deploy-button {
  height: 48px;
  font-size: 16px;
  font-weight: 500;
}

.action-links {
  display: flex;
  justify-content: space-around;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
}

/* 统计区域 */
.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  height: 100%;
  transition: all 0.3s ease;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

/* 部署控制台 */
.deploy-console-card {
  margin-bottom: 24px;
}

.status-alert {
  margin-bottom: 20px;
}

.deploy-progress-section {
  margin-top: 20px;
}

.progress-title {
  font-size: 14px;
  font-weight: 500;
  color: #1890ff;
}

.progress-container {
  background: #fafafa;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #f0f0f0;
}

.deploy-progress {
  margin-bottom: 16px;
}

.progress-info {
  margin-bottom: 20px;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.progress-message {
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
}

.deploy-details {
  background: white;
  border-radius: 6px;
  padding: 16px;
  border: 1px solid #e8e8e8;
}

/* 最近部署记录 */
.recent-history-card {
  margin-bottom: 24px;
}

.history-list .history-item {
  transition: background-color 0.2s ease;
}

.history-list .history-item:hover {
  background-color: #fafafa;
}

.status-tag {
  font-weight: 500;
}

.deploy-message {
  font-weight: 500;
  color: #262626;
}

.branch-tag {
  font-size: 12px;
}

.deploy-meta {
  color: #8c8c8c;
  font-size: 13px;
}

.log-link {
  color: #1890ff;
  transition: color 0.2s ease;
}

.log-link:hover {
  color: #40a9ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard {
    padding: 0 8px;
  }
  
  .overview-section,
  .stats-section {
    margin-bottom: 16px;
  }
  
  .deploy-console-card,
  .recent-history-card {
    margin-bottom: 16px;
  }
  
  .progress-container {
    padding: 16px;
  }
  
  .deploy-details {
    padding: 12px;
  }
  
  .action-links {
    flex-direction: column;
    gap: 8px;
  }
}

@media (max-width: 576px) {
  .deploy-button {
    height: 40px;
    font-size: 14px;
  }
  
  .progress-title {
    font-size: 13px;
  }
  
  .deploy-meta {
    font-size: 12px;
  }
}

/* 日志模态框样式 */
.log-content {
  background: #1e1e1e;
  color: #d4d4d4;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
  padding: 16px;
  border-radius: 4px;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 400px;
  overflow-y: auto;
}

.log-content::-webkit-scrollbar {
  width: 8px;
}

.log-content::-webkit-scrollbar-track {
  background: #2d2d2d;
  border-radius: 4px;
}

.log-content::-webkit-scrollbar-thumb {
  background: #555;
  border-radius: 4px;
}

.log-content::-webkit-scrollbar-thumb:hover {
  background: #777;
}
</style>